package com.bit.cfdi.web.services;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class MailService {
	
	private Logger log = LogManager.getLogger(this.getClass().getName());

	@Autowired
	private JavaMailSender mailSender;
	
	public void sendMail(final String from, final String to, 
				final String subject, final String msg) throws Exception {
		
		try {
			MimeMessage message2 = mailSender.createMimeMessage();
			message2.setFrom(new InternetAddress(from));
			message2.setRecipient(Message.RecipientType.TO, 
					new InternetAddress(to));
			message2.setSubject(subject);
			MimeMessageHelper helper = new MimeMessageHelper(message2, true);
			helper.setText(msg, true);
			mailSender.send(message2);
		}catch(MessagingException me) {
			log.error("ERROR: creating message" + me.getMessage());
			throw new Exception("Error al crear el mensaje del correo");
		}catch(MailAuthenticationException mae) {
			log.error("ERROR: sender authentification");
			throw new Exception("Error al autentificar el emisor");
		}catch(MailSendException mse) {
			log.error("ERROR: sending email");
			throw new Exception("Error al mandar el correo");
		}
	}
	
}
